package com.zjw.jdbc.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * the jdbc util 
 * @author zjw
 *
 */
public class JdbcUtil {
	private static Properties dbProp;
	private static String driverClass,username,password,jdbcUrl;
	static{
		loadProp();
		readDbInfo();
		registerDriver();
	}
	private static void loadProp(){
		dbProp = new Properties();
		try {
			String name ="/jdbc.properties";
			InputStream is = JdbcUtil.class.getResourceAsStream(name);
			dbProp.load(is);
		} catch(IOException e) {
			e.printStackTrace();
		}
	}
	
	private static void readDbInfo(){
		driverClass = dbProp.getProperty("jdbc.driver","com.mysql.jdbc.Driver");
		username = dbProp.getProperty("jdbc.user","root");
		password = dbProp.getProperty("jdbc.password","root");
		jdbcUrl = dbProp.getProperty("jdbc.url","jdbc:mysql:///test");
	}
	
	private static void registerDriver(){
		try {
			Class.forName(driverClass);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	/**
	 * get connection without pool
	 * @return
	 * @throws SQLException 
	 */
	public static Connection getConnection() throws SQLException{
		return DriverManager.getConnection(jdbcUrl, username, password);
	}
	
	/**
	 * release the database resource
	 * @param resultSet
	 * @param statement
	 * @param conn
	 */
	public static void releaseDB(ResultSet resultSet,Statement statement,Connection conn){
		//close order:resultSet --> statement --> connection
		closeResultSet(resultSet);
		closeStatement(statement);
		closeConnection(conn);
	}
	
	/**
	 * close Connection quietly
	 * @param conn
	 */
	public static void closeConnection(Connection conn){
		if(null != conn){
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * close Statement quietly
	 * @param statement
	 */
	public static void closeStatement(Statement statement){
		if(null != statement){
			try {
				statement.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * close ResultSet quietly
	 * @param resultSet
	 */
	public static void closeResultSet(ResultSet resultSet){
		if(null != resultSet){
			try {
				resultSet.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * rollback connection quietly
	 * @param conn
	 */
	public static void rollback(Connection conn){
		if(null != conn){
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

}
